package com.hdhere.core.configuration;

import com.hdhere.core.util.EnvironmentHolder;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Created by dus on 2018/11/3.
 */
@Configuration
@EnableSwagger2
@ConditionalOnWebApplication
public class SwaggerConfig extends WebMvcConfigurerAdapter/* implements WebMvcConfigurer*/ {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("redirect:/swagger-ui.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }

    @Bean
    public Docket createRestApi() {

        boolean useApi = false;
        String apiOpen = EnvironmentHolder.getProperty("apiOpen");// 如果开启api 不判断环境，否则默认非生产环境下开启
        if (StringUtils.isNotBlank(apiOpen))
            useApi = true;
        else {
            String active = EnvironmentHolder.getProperty("spring.profiles.active");
            if (!"prod".equalsIgnoreCase(active))
                useApi = true;
        }
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(useApi ? PathSelectors.any() : PathSelectors.none())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("hdhere系统api文档")
                .description("")
                .termsOfServiceUrl("http://localhost:8090/")
                .contact("dustin")
                .version("1.0.0")
                .build();
    }
}
